package com.woparker.kiosk.utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowInsets;
import android.view.WindowManager;

import androidx.core.app.ActivityCompat;

import com.woparker.kiosk.KioskApplication;
import com.woparker.kiosk.R;
import com.woparker.kiosk.base.ContextHolder;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonUtils {
    //是否是8个方位寻路
    public static final boolean IS_DERECTION_EIGHT = false;
    //退格
    public static String backspaceTool(String str) {
        String string = "";
        if (str == null || str.length() <= 0) {
            return string;
        }
        string = str.substring(0, str.length() - 1);
        return string;
    }

    public static int[] getScreenSize() {
        WindowManager wm = (WindowManager) ContextHolder.getAppContext().getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();
        int[] size = new int[2];
        size[0] = width;
        size[1] = height;
        return size;
    }
    //去掉特殊字符
    public static String replaceBlank(String str) {
        String dest = "";
        if (str!=null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }
    /**
     * 设置画笔
     *
     * @param paint
     * @return
     */
    public static Paint getDividerPaint(Paint paint) {
        if (paint == null) {
            paint = new Paint();
        }
        float strokeWidth = 8.0f;
        //颜色
        paint.setColor(Color.alpha(0));
        paint.setStrokeWidth(strokeWidth);
        paint.setAlpha(0);
        return paint;
    }

    //获取视图bitmap
    public static Bitmap getCache(View contentLayout){
        contentLayout.setDrawingCacheEnabled(true);
        contentLayout.measure(
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        contentLayout.layout(0, 0, contentLayout.getMeasuredWidth(),
                contentLayout.getMeasuredHeight());
        contentLayout.buildDrawingCache();
        return contentLayout.getDrawingCache();
    }

    public static String getTime(long timeInMillis){
        Instant instant = Instant.ofEpochMilli(timeInMillis);
        ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDate = zdt.format(formatter);
        return formattedDate;
    }

    public static String getCurrentFormattedTime() {
        // 定义时间格式，例如 "yyyy-MM-dd HH:mm:ss"
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        // 获取当前时间
        Date currentTime =new Date();
        // 格式化当前时间
        return dateFormat.format(currentTime);
    }

    public static Bitmap getBitmapFromResource(Resources resources, int resourceId) {
        // 创建 BitmapFactory.Options 对象
        BitmapFactory.Options options = new BitmapFactory.Options();
        // 设置 inJustDecodeBounds 为 false，加载完整的 Bitmap
        options.inJustDecodeBounds = false;
        // 加载完整的 Bitmap
        return BitmapFactory.decodeResource(resources, resourceId, options);
    }

    public static String getMacAddress(Context context) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (wifiManager != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // For Android 6.0 and above
                if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    Log.e("MacAddressFetcher", "Location permission is not granted");
                    return null;
                }
                wifiManager.startScan();
                List<ScanResult> scanResults = wifiManager.getScanResults();
                for (ScanResult scanResult : scanResults) {
                    if (scanResult.BSSID != null) {
                        return scanResult.BSSID;
                    }
                }
            } else {
                // For Android 5.1 and below
                return wifiManager.getConnectionInfo().getMacAddress();
            }
        }
        return ContextHolder.getAppContext().getString(R.string.unknown);
    }

    @SuppressLint("DefaultLocale")
    public static String getWifiIpAddress(Context context) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (wifiManager != null && wifiManager.isWifiEnabled()) {
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            int ipAddress = wifiInfo.getIpAddress();
            return String.format("%d.%d.%d.%d",
                    (ipAddress & 0xff),
                    (ipAddress >> 8 & 0xff),
                    (ipAddress >> 16 & 0xff),
                    (ipAddress >> 24 & 0xff));
        }
        return ContextHolder.getAppContext().getString(R.string.unknown);
    }

    public static String getAppVersion(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            String versionName = packageInfo.versionName;
            int versionCode = packageInfo.versionCode;
            Log.d("VersionFetcher", "Version Name: " + versionName);
            Log.d("VersionFetcher", "Version Code: " + versionCode);
            return versionName;
        } catch (PackageManager.NameNotFoundException e) {
            Log.e("VersionFetcher", "Package name not found", e);
        }
        return "V1.0";
    }

    public static int getStatusBarHeight(Context context) {
        int statusBarHeight = 0;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            Display defaultDisplay = windowManager.getDefaultDisplay();
            DisplayMetrics metrics = new DisplayMetrics();
            defaultDisplay.getMetrics(metrics);
            DisplayMetrics realMetrics = new DisplayMetrics();
            defaultDisplay.getRealMetrics(realMetrics);
            statusBarHeight = realMetrics.heightPixels - metrics.heightPixels;
        }
        return statusBarHeight;
    }



}
